<?php

class MemberModel extends Model {

	public $loginError;

	public $userInfo;

	private $mtomdb;

	

	protected $_validate = array(

		array('repassword','password','两次输入的密码不相同',0,'confirm'),

	);

	public function _initialize(){

		parent::_initialize();

		$this->mtomdb = M('Member_member');

	}

	public function _list($view,$map,$sort='sort',$pagesize=20){

		//计算总页数

		$map['n.pid'] = 0;

		$count=$this->count($map);

		//实例化分页类

		import ( 'ORG.Util.Page' );

		$p=new Page($count,$pagesize);

		$list = $this->where($map)->alias('n')->join("left join __MEMBER_GROUP__ AS c on c.id=n.group_id")->Field("n.*,c.title as group_title")->order($sort)->limit($p->firstRow.','.$p->listRows)->select();

        foreach($list as $k => $v){

		    $list[$k]['sub'] = $this-> getListToArray1($v['id'], __RELATEID__);

		}

        $pages=$p->show();

		$view->assign('list',$list);

		$view->assign('pages',$pages);

	}

    public function __list($view,$map,$sort='sort',$pagesize=20){

		//计算总页数

		$count=$this->count($map);

		//实例化分页类

		import ( 'ORG.Util.Page' );

		$p=new Page($count,$pagesize);

		$list = $this->where($map)->alias('n')->join("left join __MEMBER_GROUP__  AS c on c.id=n.group_id")->Field("n.*,c.title as group_title")->order($sort)->limit($p->firstRow.',

'.$p->listRows)->select();

        

        $pages=$p->show();

		$view->assign('list',$list);

		$view->assign('pages',$pages);

	}



    public function _listGroup($view,$join, $field,$map,$sort='sort',$group='m.id',$rename = 'm',$pagesize=20) {

		//计算总页数

		$count = $this->alias($rename)->join($join)->where($map)->group($group)->count2();

		import('ORG.Util.Page');

		//实例化分页类

		$p = new Page($count, $pagesize);

		$list = $this->alias($rename)->join($join)->where($map)->Field($field)->order($sort)->group($group)->limit($p->firstRow . ',' . $p->listRows)->select();

		$pages = $p->show();

		$_GET['list']=$list;

		$view->assign('list',$list);

		$view->assign('pages',$pages);

    }

	//获取所有员工的视图

	public function getMemberView($view,$class='member'){

		$data=M('class_view')->where(['class'=>$class])->getField('value');

		$members=$this->getallgroupmember2();

		$view->assign('memberlist',$members);

		$result=$view->fetch('',$data);

		die($result);

		//die(json_encode(['statu'=>1,'result'=>$result]));

	}

	

    //获取所有部门下除了当前会员的人员

	public function getallgroupmember(){

        $depart=M('member_position')->where(array("status"=>1,"site_id"=>__SITEID__))->select();

        $arr=array();

        $map['m.id']=array('neq',session(C('USER_AUTH_KEY')));

        foreach($depart as $val){

            $map['g.id']=$val['id'];

            $staffs=$this->alias('m')->join("left join __MEMBER_POSITION__ g on g.id=m.position_id")->where($map)->Field("m.*")->select();

            $arr[$val['name']]=$staffs;

        }

        return $arr;

    }

    //获取所有部门下的所有人员

	public function getallgroupmember2(){

        $depart=M('member_position')->where(array("status"=>1,"site_id"=>__SITEID__))->select();

        $arr=array();

        foreach($depart as $val){

            $map['g.id']=$val['id'];

            $staffs=$this->alias('m')->join("left join __MEMBER_POSITION__ g on g.id=m.position_id")->where($map)->Field("m.*")->select();

            $arr[$val['name']]=$staffs;

        }

        return $arr;

    }

    //获取相应部门的员工

	public function getgroupmember($pid){

        $map['g.id']=$pid;

        $staffs=$this->alias('m')->join("left join __MEMBER_POSITION__ g on g.id=m.position_id")->where($map)->Field("m.*")->select();

        return $staffs;

    }

    //获取相应部门除了当前会员的员工

	public function getgroupmember2($pid){

        $map['g.id']=$pid;

        $map['m.id']=array('neq',session(C('USER_AUTH_KEY')));

        $staffs=$this->alias('m')->join("left join __MEMBER_POSITION__ g on g.id=m.position_id")->where($map)->Field("m.*")->select();

        return $staffs;

    }

	private function count2($map){

		$re = $this->alias('m')->where($map)->Field('count(*) as tp_count')->find();

		return $re['tp_count'];

	}

	private function count($map){

		$re = $this->alias('n')->where($map)->Field('count(*) as tp_count')->find();

		return $re['tp_count'];

	}

	public function getListToArray1($pid=0,$siteid=0,$deep=0,$arr=array()){

		$re=$this->where(array('pid'=>$pid,'site_id'=>$siteid))->order('sort')->select();

		if($re!==false){

			$deep++;

			foreach($re as $k=>$v){

				$v['deep']=$deep;

				$arr[]=$v;

				$arr=$this->getListToArray1($v['id'],$siteid,$deep,$arr);

			}

			return $arr;

		}

	}

	

	public function getListToCount1($pid=0,$siteid=0,$deep=0,$arr=array()){

		$re=$this->where(array('pid'=>$pid,'site_id'=>$siteid))->order('sort')->Field('id,pid,level')->select();

		if($re!==false){

			$deep++;

			foreach($re as $k=>$v){

				$v['deep']=$deep;

				$arr[]=$v;

				$arr=$this->getListToCount1($v['id'],$siteid,$deep,$arr);

			}

			return $arr;

		}

	}

	

	public function getListToCount($pid=0,$siteid=0,$deep=0,$arr=array()){

		return count($this->getListToCount1($pid,$siteid,$deep,$arr));	

	}

	

	public function checkLogin($map){

		$re = $this->where($map)->find();

		if(!is_array($re)){

			$this->loginError='用户名或密码错误';

			return false;

		}else{

			$this->userInfo=$re;

			//更新用户信息

            $data['login_ip'] = get_client_ip();

			$data['login_time'] = time();

			$this -> where(array('id' => $re['id'])) -> data($data) -> save();

			return true;

		}

	}



	public function checkName($map){

		$re=$this->where("username = '".$map."'")->find();

		if($re){

			return $map;

		}elseif($this->where("number = '".$map."'")->find()){

			$name=$this->where("number = '".$map."'")->getfield('username');

			return $name;

		}elseif($map!='' && $this->where("tel = '".$map."'")->find()){

			$name=$this->where("tel = '".$map."'")->getfield('username');

			return $name;

		}else{

			return $map;

		}

	}

	

	//检查是否可以绑定PID

	public function checkPid($member_id, $pid){

		//不能绑定自己

		if($member_id == $pid || $this->checkSubMember($member_id, $pid)){

		    return false;

		}

		return true;

	}

	//检查会员是否为自己的子级会员

	public function checkSubMember($member_id, $pid){

		$member = $this -> where(array('id' => $pid)) -> find();

		//dump($member);

		if(!$member){

			return false;

		}

		if($member && $member['pid'] == $member_id){

			return true;

	    }

		

		return $this->checkSubMember($member_id, $member['pid']);

	}

	//记录会员的无限级关系

	public function member_to_member1($pid=0,$member_id = 0){

		//先删除关系，再重新写入

		$this -> mtomdb -> where(array('smember_id' => $member_id, 'level' => array('gt', 0))) -> delete();

		$re=$this->where(array('id'=>$pid, 'level' => array('gt', 0)))->find();

		$re['deep'] = $deep + 1;

		$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;

		

		if(!$this -> where(array('id' => $member_id)) -> find()){

			return false;

		}

		

		

		$this -> mtomdb -> data(array('datetime' => time(), 'site_id' => $site_id, 'member_id' => $pid, 'smember_id' => $member_id, 'level' => $this -> where(array('id' => $member_id)) -> getField('level'), 'deep' => 1, 'is_subscribe' => $this -> where(array('id' => $member_id)) -> getField('is_subscribe'))) -> add();

//		echo $member_id.'--'.$this -> where(array('id' => $member_id)) -> getField('level');

//		dump($pid. '-->'. $member_id);

		

		//第二层

		//$member_id = $pid;

		$pid = (int)M('Member_connect') -> where(array('type' => array('gt', 0), 'referee_id' => $pid, 'type' => array('gt', 0))) -> getField('member_id');

		if($pid > 0){

			$this -> mtomdb -> data(array('datetime' => time(), 'site_id' => $site_id, 'member_id' => $pid, 'smember_id' => $member_id, 'level' => $this -> where(array('id' => $member_id)) -> getField('level'), 'deep' => 2, 'is_subscribe' => $this -> where(array('id' => $member_id)) -> getField('is_subscribe'))) -> add();

//			dump($pid. '-->'. $member_id);

			//第三层

			//$member_id = $pid;

		    $pid = (int)M('Member_connect') -> where(array('referee_id' => $pid, 'type' => array('gt', 0))) -> getField('member_id');

			if($pid > 0){

				$this -> mtomdb -> data(array('datetime' => time(), 'site_id' => $site_id, 'member_id' => $pid, 'smember_id' => $member_id, 'level' => $this -> where(array('id' => $member_id)) -> getField('level'), 'deep' => 3, 'is_subscribe' => $this -> where(array('id' => $member_id)) -> getField('is_subscribe'))) -> add();

//				dump($pid. '-->'. $member_id);

			}

		}

    }

	//记录会员的无限级关系

	public function member_to_member($pid=0,$member_id = 0, $deep = 0){

		$re=$this->where(array('id'=>$pid))->find();

		if(!is_array($re)){

			return;

		}else{

			$re['deep'] = $deep + 1;

			$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;

			//$this -> mtomdb -> data(array('datetime' => time(), 'site_id' => $site_id, 'member_id' => $pid, 'smember_id' => $member_id, 'level' => $this -> where(array('id' => $member_id)) -> getField('level'), 'deep' => $re['deep'], 'is_subscribe' => $this -> where(array('id' => $member_id)) -> getField('is_subscribe'))) -> add();

			$this -> mtomdb -> data(array('datetime' => time(), 'site_id' => $site_id, 'member_id' => $pid, 'smember_id' => $member_id, 'level' => 0, 'deep' => $re['deep'], 'is_subscribe' => $this -> where(array('id' => $member_id)) -> getField('is_subscribe'))) -> add();

			$deep ++;

			$this->member_to_member($re['pid'], $member_id, $deep);

		}

    }

	//返回代理商总数 

	public function getLevel1Count($member_id, $level = 0, $deep = 0){

		$map['member_id'] = $member_id;

		if($deep > 0){

			$map['deep'] = array('elt', $deep);

		}

		if($level > 0){

			$map['level'] = array('egt', $level);

		}

		$db = M('Member_member');

		$ret = $db-> where($map) -> count();

		//echo $db -> getLastSql();

		return $ret;

	}

	//更新用户的父级ID

	public function updatePid($member_id, $pid){

		$mpid = $this -> where(array('id' => $member_id)) -> getField('pid');

		if(!$this -> where(array('id' => $mpid)) -> find()){

			$mpid = 0;

		}

		if($this->checkPid($member_id, $pid) && $mpid == 0){

			$ret = $this -> where(array('id' => $member_id)) -> data(array('pid' => $pid)) -> save();

			//删除关系

			$Member_memberdb = M('Member_member');

			$Member_memberdb -> where(array('smember_id' => $member_id, 'level' => 0)) -> delete();

			//重新生成关系

			

			$memberList = $Member_memberdb -> where(array('member_id' => $member_id)) -> select();

			foreach($memberList as $v){

				//$Member_memberdb -> where(array('smember_id' => $v['smember_id'])) -> delete();

				$this->member_to_member($pid, $v['smember_id'], $v['deep']);

			}

			$this->member_to_member($pid, $member_id);

			return true;

		}

		return false;

	}



	public function deletePid($member_id, $pid){

		$db = M('Member_member');

		$sql = $db -> where(array('member_id' => $member_id)) -> Field('smember_id as smember_id') -> buildSql();

		$list = $db -> where("member_id = '".$pid."' and smember_id in(".$sql.")") -> select();

		//echo $db -> getLastSql();

		//dump($list);

		foreach($list as $v){

			$db -> where(array('member_id' => $pid, 'smember_id' => $v['smember_id'], 'level' => 0)) -> delete();

		}

		$ret = $this -> where(array('id' => $member_id)) -> data(array('pid' => 0)) -> save();

		return $ret;

	}



	public function getUserArr($pid=0,$arr=array(), $deep = 0, $cd = 3){

		$re=$this->where(array('id'=>$pid))->find();

		//8级返回

		if($deep == $cd){return $arr;}

		if(!is_array($re)){

			return $arr;

		}else{

			$re['deep'] = $deep + 1;

			$arr[]=$re;

			$deep ++;

			return $this->getUserArr($re['pid'],$arr, $deep, $cd);

		}

	}



	//获取用户级别名称

	public function getLevelName($mid){

		$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;

		$v = $payment = M('Affiliatesetting') -> where(array('site_id' => $site_id, 'status' => 1)) -> find();

		if(!$v){

			return '';

		}

		import("@.ORG.Affiliate.".$v['classname']);

		$class = $v['classname'];

		$Threelevel = new $class(0, $site_id, $mid);

		return $Threelevel -> getLevelName();

	}

	

	//获取用户级别名称列表

	public function getLevelNameList(){

		$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;

		$v = $payment = M('Affiliatesetting') -> where(array('site_id' => $site_id, 'status' => 1)) -> find();

		if(!$v){

			return '';

		}

		import("@.ORG.Affiliate.".$v['classname']);

		$class = $v['classname'];

		$Threelevel = new $class(0, $site_id, 0);

		

		return $Threelevel -> getLevelNameList();

	}

	

	//更新微信用户

	public function savewx($login_result){

	   //会员表信息

		//$user['site_id']=__RELATEID__;

		//$user['openid']=$login_result['openid'];



		$data = $this->where(array('id' => $login_result['id']))->find();

		if($data['nickname'] != ''){

			unset($login_result['nickname']);

		}

		if($login_result['nickname'] != '' ){

		    $user['nickname']=parseWeixinName( $login_result['nickname']);

		}

		if($login_result['headimgurl'] != '' && $data['img_url'] == ''){

		    $user['img_url'] = $login_result['headimgurl'];

		}

		if($user['reg_time'] == ''){

		    $user['reg_time'] = time();

		}

		$user['is_subscribe'] = $login_result['subscribe'];

		

		$user['sex'] = intval($login_result['sex']);

		if($data['username']==''){

			$user['username'] = 'weixin'.$login_result['id'];

		}

		//$user['reg_time'] = time();

		//插入会员

		$member_id=$login_result['id'];

	   

		$id=$this->where("id=$member_id")->save($user);

		$this->addUser($member_id);

		/*echo $this-> getLastSql();

		dump($login_result);exit;*/

		

		$data = $this->where(array('id' => $member_id))->find();

	   //  dump($data); exit(); 

		session('memberInfo',$data);

		 //名片表信息

		return true;

  	}



	public function addUser($member_id){

		$data['member_id']=$member_id;

		$data=$this->where('id = '.$member_id)->find();

		$data['member_id']=$data['id'];

		unset($data['id']);

		if($data['remark']=='')$data['remark']='  ';

		if($data['email']=='')$data['email']='  ';

		if($data['nickname'])$data['nickname']=$data['username'];

		$data['status']=1;

		$data['pid']=0;

		

		$data['account']=$data['username'];

        $roleid=8;//默认消费者

		if(D('User')->where('member_id = '.$member_id)->find()) {

			$userid=D('User')->where('member_id = '.$member_id)->getfield('id');

			D('User')->where('member_id ='.$data['member_id'])->save($data);

		}else{

			if($data['account']){

				$userid=D('User')->add($data);

			}

        }

        if($userid){

            if(D('Role_user')->where('user_id = '.$userid)->find()){

				switch($data['level']){

					case 0:$roleid=8;break;

					case 1:$roleid=1;break;

					case 2:

					case 3:

					case 4:$roleid=4;break;

					case 5:$roleid=5;break;

					case 6:$roleid=4;break;

					default:$roleid = 8;break;

				}

				D('Role_user')->where('user_id = '.$userid)->data(['role_id'=>$roleid])->save();

            }else{

                D('Role_user')->data(['role_id'=>$roleid,'user_id'=>$userid])->add();

                $siteuser['site_id'] = 143;

                $siteuser['user_id'] = $userid;

				if(!D('Site_user')->where('site_id = 143 and user_id = '.$userid)->find()){

					M('Site_user') -> add($siteuser);

				}

            }

            return true;

        }else{

            return false;

        }

	}

	  

	  //用户充值处理

	public function savemoney($order_id){

		  //901定义为充值

		  //查询是否是充值订单

		  $orderdb = M('Order');

		  $order = $orderdb -> where(array('id' => $order_id, 'status' => 2, 'confirm' => 0)) -> find();

		  if(!$order || $order['savemoney'] == 0){

			  return false;

		  }else{

			  $maldb = D('Member_account_log');

			  $ret = $maldb -> change($order['total'], $order['member_id'], '在线充值', '901');

			  if($ret){

				  //订单确认

				  $orderdb -> where(array('id' => $order_id)) -> data(array('shipping_status' => 4, 'confirm' => 1)) -> save(); 

				  M('Sale') -> where(array('order_id' => $order_id)) -> data(array('status' => 1, 'confirm' => 1)) -> save();

			  }else{

				  return false;

			  }

		  }

		  

	  }

	public function isLeader($member){

		$isadmin=$this->where('id = '.$member)->getfield('isadministrator',false);

		if($isadmin){//老板

			return true;

		}else{

			$isLeader=D('Member_position')->where('member_id = '.$member)->find();

			if($isLeader){//主管

				return true;

			}else{

				$intmanager=getManagerList();

				if(in_array($member,$intmanager)){//积分管理员

					return true;

				}else{

					return false;

				}

			}

		}

	}

	public function getTeamMember($pid){

		//getfield true 数组，false 单个

		$id=$this->where('memberpositionid like ",'.$pid.',"')->getfield('id',true);

		return $id;

	}

	public function connect($data){

	    $id=$data['member_id'];

	    $find=D('Member_connect')->where($data)->select();

        //表中是否有二者的关系

	    if(!$find){

            //表中是否已有这个referee_id,referee_id唯一

	        $checktrue=D('Member_connect')->where('referee_id = '.$data['referee_id'])->find();

	        if(!$checktrue){

                $res=D('Member_connect')->add($data);

                if($res){

                    $this->member_to_member1($id,$data['referee_id']);

                }else{

                    return $res;

                }

            }else{

	            return '当前服务商已经被关联';

            }

        }else{

	        return '您已关联当前服务商';

        }

    }

	//更改会员等级

    public function changeLevel($data){

	    $d['referee_id']=$data['id'];

	    $d['type']=$data['level'];

//	    if(D('Member')->where('id = '.$data['id'])->getfield('level')=='1'){

//	        return array('status'=>0,'info'=>'更新失败：商家不允许升级!');

//        }

	    $found=D('Member_connect')->where('referee_id ='.$d['referee_id'])->find();

        if($found){

            $re=D('Member_connect')->where('referee_id = '.$d['referee_id'])->data(array('type'=>$d['type']))->save();

        }

		$find=D('Member_member')->where('smember_id = '.$d['referee_id'])->find();

		if($find){

			$mm=D('Member_member')->where('smember_id = '.$d['referee_id'])->data(array('level'=>$d['type']))->save();

		}

        $r = isset($re) ? $re :true;

        if($r){

            $res=$this->where('id ='.$d['referee_id'])->data(array('level'=>$d['type']))->save();

        }

        $rr=isset($res)?$res :false;

        if($rr){

			$mdata=D('Member')->where('id = '.$d['referee_id'])->field('username,nickname,login_time,login_ip,remark,email,id')->find();

			$mdata['member_id']=$mdata['id'];

			unset($mdata['id']);

			$mdata['last_login_time']=$mdata['login_time'];

			unset($mdata['login_time']);

			$mdata['last_login_ip']=$mdata['login_ip'];

			unset($mdata['login_ip']);

			$mdata['account']=$mdata['username'];

			unset($mdata['username']);

			if($mdata['remark']=='')$mdata['remark']='  ';

			if($mdata['email']=='')$mdata['email']='  ';

			$mdata['password']=md5('123456');

			$mdata['status']=1;

			$mdata['pid']=0;

			$userid=D('User')->where('member_id = '.$d['referee_id'])->getfield('id');

			/*if($userid==null){

				$adduser=D('User')->add($mdata);

				$datas['user_id'] = $adduser;

				$datas['site_id'] = 143;

				M('Site_user') -> add($datas);

			}*/

			$userid=(int)D('User')->where('member_id = '.$d['referee_id'])->getfield('id');

            if($d['type']==6){//服务商6

                $roleid=4;

            }elseif($d['type']==5){//业务员5

                $roleid=5;

            }elseif($d['type']<5&&$d['type']>1){//代理2-4

                $roleid=4;

            }elseif($d['type']==0){//消费者0

                $roleid=8;

            }elseif($d['type']==1){//商家1

                $roleid=1;

            }

            if(D('Role_user')->where('user_id = '.$userid)->find()){

                D('Role_user')->where('user_id = '.$userid)->data(['role_id'=>$roleid])->save();

            }else{

                D('Role_user')->data(['role_id'=>$roleid,'user_id'=>$userid])->add();

            }

			$this->changeNumber($data['id'],$data['level']);

            return array('status'=>1,'info'=>'更新成功');

        }else{

            return array('status'=>0,'info'=>'更新失败');

        }

    }

	public function getMaxNumber($level=NULL){

		$data=array(0=>'2',1=>'S',2=>'D',3=>'D',4=>'D',5=>'Y',6=>'F');

		$str='';

		if($level){$str=$data[$level];}else{$str=2;}

		$num=$this->where(' number like "'.$str.'%"')->order('n desc')->Field('CONVERT(substring(number, 2), SIGNED) as n') -> find();

		$num=$num['n'];

		return $num+1;

	}

	public function fitNumber($level,$num){

	    if($level==0){

	        if($num<1000){$num=str_pad($num,3,"0",STR_PAD_LEFT);}else{$num=$num;}

            $num='2'.$num;

        }elseif($level == 1){//S

            $num='S'.$num;

        }elseif($level == 5){//Y

            $num='Y'.$num;

        }elseif($level == 6){//F

            $num='F'.$num;

        }else{//D

            $num='D'.$num;

        }

        return $num;

    }

	public function checkEmpty(){

	    $res=$this->where("number = '' ")->count();

	    if($res){

	        $re=$this->where('number = "" ')->order('id')->find();

			if($re){

				$level=$re['level'];

				$num=$this->getMaxNumber($level);

				$num=$this->fitNumber($level,$num);

				$save=$this->where('id = '.$re['id'])->save(array('number'=>$num));

				if($save){

					$res=$this->where("number = '' ")->count();

					if($res){

						return $this->checkEmpty();

					}

				}



			}

        }

    }

	public function changeNumber($id,$level){

		$num=$this->fitNumber($level,$this->getMaxNumber($level));

		$this->where('id = '.$id)->save(array('number'=>$num));

	}

    public function getChildrens($view,$id,$deep=0,$pagesize=10){

        //计算总页数

        $deep1=$this -> where('pid = '.$id) -> getfield('id',true);

        $all=$deep1;

        $deep2=array();

        foreach($deep1 as $k => $v){

            $sec=$this->where('pid = '.$v)->getfield('id',true);

            foreach($sec as $key => $val){

                if(!in_array($val,$deep2)){

                    array_push($deep2,$val);

                }

            }

        }

        foreach($deep2 as $kk => $vv){

            if(!in_array($vv,$deep1)){

                array_push($all,$vv);

            }

        }

        if($deep ==0){

            $kids=$all;

        }elseif($deep==1){

            $kids=$deep1;

        }elseif($deep==2){

            $kids=$deep2;

        }

        $count=count($kids);

        import ( 'ORG.Util.Page' );

        $p=new Page($count,$pagesize);

        if(count($kids)){

            $where='id in ('.implode(',',$kids).')';

            $list=$this->where($where)->limit($p->firstRow.','.$p->listRows)->select();

        }

        $pages=$p->show();

        $view->assign('list',$list);

        $view->assign('pages',$pages);

    }

}